package com.jajb.controldeiluminacion;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;


public class BluetoothHelper extends Activity {

    // Direccion MAC del bluetooth host (cambiar por el que coorresponda)
    private static final String address = "00:13:12:12:65:87";

    //Serial Port Profile (SPP)
    private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    //Request para habilitar bluetooth
    public static final int REQUEST_ENABLE_BLUETOOTH = 1;

    //Identificador para mensajes desde el bluetooth
    public static final int RECEIVE_MESSAGE_BLUETOOTH = 1;

    private BluetoothDevice btdevice = null;
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    public ConnectedThread btConnectedThread = null;
    private Handler handler;

    public String error = "";


    public BluetoothHelper(Handler h) {
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        btdevice = btAdapter.getRemoteDevice(address);
        handler = h;
    }

    // Metodo para conectar al dispositivo
    public boolean Conecta() {
        try {
            btSocket = btdevice.createRfcommSocketToServiceRecord(SPP_UUID);
        } catch (IOException e) {
            error = e.getMessage();
            return false;
        }

        if (btAdapter.isDiscovering()) {
            btAdapter.cancelDiscovery();
        }

        try {
            btSocket.connect();

            btConnectedThread = new ConnectedThread(btSocket);
            btConnectedThread.start();
        } catch (IOException e) {
            try {
                btSocket.close();
                error = e.getMessage();
                return false;
            } catch (IOException e2) {
                error = e2.getMessage();
                return false;
            }
        }

        return true;
    }


    // Metodo para desconectar del dispositivo
    public void Desconecta() {

        if (btAdapter.isEnabled()) {
            try {
                btSocket.close();
            } catch (IOException e) {
            }
        }
    }


    // Metodo para habilitar el bluetooth
    public void Habilita() {
        if (btAdapter != null) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLUETOOTH);
        }
    }


    // Metodo para deshabilitar el bluetooth
    public void Deshabilita() {
        if (btAdapter.isEnabled()) {
            btAdapter.disable();
        }
    }


    // Metodo para verificar si esta habilitado el bluetooth
    public boolean EsHabilitado() {
        return btAdapter.isEnabled();
    }


    // Metodo para obtener el estado del bluetooth
    public int ObtieneEstado() {
        return btAdapter.getState();
    }


//----------------------------------------------------------------------------------------------------------
// CLASES
//----------------------------------------------------------------------------------------------------------

    public final class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        //------------------------------------------------------------------------------------
        //Conexion al thread por medio del socket

        private ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        //------------------------------------------------------------------------------------
        //Ejecuta el thread y recibe los mensajes del host

        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;

            while (true) {
                try {
                    if (mmInStream.available() > 0) {
                        bytes = mmInStream.read(buffer);
                        handler.obtainMessage(RECEIVE_MESSAGE_BLUETOOTH, bytes, -1, buffer).sendToTarget();
                    }
                } catch (IOException e) {
                    break;
                }
            }
        }

        //------------------------------------------------------------------------------------
        //Envia mensajes al host

        public void write(String message) {
            byte[] msgBuffer = message.getBytes();

            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
            }
        }
    }
}
